<template>
  <child-page>
    <div class="components-form-demo-advanced-search">
      <a-form
        class="ant-advanced-search-form"
        :form="form"
        @submit="handleSubmit"
      >
        <a-form-item v-bind="formItemLayout" label="上级节点">
          <a-tree-select
            showSearch
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择上级节点"
            allowClear
            treeNodeFilterProp="title"
            treeDefaultExpandAll
            @change="onChange"
            v-decorator="[
              'pid',
              {
                initialValue: initInfo.pid,
                rules: [{ required: true, message: '必选项' }]
              }
            ]"
          >
            <a-tree-select-node
              v-for="item in athList"
              :value="item.id"
              :title="item.title"
              :key="item.id"
            >
              <a-tree-select-node
                v-for="i in item.children"
                :value="i.id"
                :title="i.title"
                :key="i.id"
              >
                <a-tree-select-node
                  v-for="n in i.children"
                  :value="n.id"
                  :title="n.title"
                  :key="n.id"
                />
              </a-tree-select-node>
            </a-tree-select-node>
          </a-tree-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="节点名称">
          <a-input
            v-decorator="[
              'title',
              { initialValue: initInfo.title, rules: rule.nodeName }
            ]"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="节点地址">
          <a-input
            v-decorator="[
              'name',
              { initialValue: initInfo.name, rules: rule.nodeSite }
            ]"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="唯一字段">
          <a-input
            v-decorator="[
              'unique_key',
              { initialValue: initInfo.unique_key, rules: rule.field }
            ]"
          />
        </a-form-item>

        <a-form-item label="节点类型" v-bind="formItemLayout">
          <a-select
            v-decorator="[
              'level',
              {
                initialValue: initInfo.level,
                rules: [{ required: true, message: '必选项' }]
              }
            ]"
          >
            <a-select-option value="1" v-if="currentLevel == 0">
              项目
            </a-select-option>
            <a-select-option value="2" v-else-if="currentLevel == 1">
              模块
            </a-select-option>
            <a-select-option value="3" v-else-if="currentLevel == 2">
              操作
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否为菜单" v-bind="formItemLayout">
          <a-select
            v-decorator="[
              'ismenu',
              {
                initialValue: initInfo.ismenu,
                rules: [{ required: true, message: '必选项' }]
              }
            ]"
          >
            <a-select-option
              value="1"
              v-if="currentLevel == 0 || currentLevel == 1"
            >
              是
            </a-select-option>
            <a-select-option value="0" v-else>
              否
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="排序">
          <a-input
            v-decorator="[
              'sorts',
              { initialValue: initInfo.sorts, rules: rule.sort }
            ]"
          />
        </a-form-item>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'center' }">
            <a-button type="primary" html-type="submit">
              提交
            </a-button>
            <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
              重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </child-page>
</template>

<script>
import childPage from "@/components/childPageContent/index";
export default {
  name: "add",
  components: {
    childPage
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      athList: [],
      statusOption: [{ label: "在用", value: 1 }, { label: "停用", value: 2 }],
      sexOption: [{ label: "男", value: 1 }, { label: "女", value: 2 }],
      rule: {
        nodeName: [{ required: true, message: "必填项" }],
        nodeSite: [{ required: true, message: "必填项" }],
        field: [{ required: true, message: "必填项" }]
      },
      initInfo: {},
      treeExpandedKeys: [],
      list: [],
      currentLevel: 1
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {
        if (!error) {
          let data = JSON.parse(JSON.stringify(values));
          if (data.level === "3" && data.ismenu === "1") {
            this.$notification.warning({
              message: "只有节点类型为项目或模块才能设置为菜单!"
            });
          } else {
            let api = null;
            if (this.$route.name === "authorityNodeAdd") {
              data.type = 1;
              api = this.$api.addAuthRule;
            } else {
              data.type = 2;
              data.id = this.$route.params.id;
              api = this.$api.editAuthRule;
            }
            this.$ajax
              .post(api, data)
              .then(() => {
                this.$notification.success({
                  message: "操作成功!"
                });
                this.$router.push({ name: "authorityNode" });
              })
              .catch(err => {
                this.$notification.error({
                  message: err
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    getJurisdictionList() {
      this.$ajax
        .get(this.$api.getAuthRuleList, {
          page_size: 1000,
          page: 1,
          excel_download: "0"
        })
        .then(res => {
          this.list = res.data;
          this.list.unshift({ id: "0", title: "顶级节点", level: 0 });
          this.athList = this.trans_tree(this.list);
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    trans_tree(jsonData) {
      //result存储json数据转为树形结构后的结果。
      //temp为临时对象，将json数据按照id值排序.
      //len是json长度，用于循环遍历结束的条件
      var result = [],
        temp = {},
        len = jsonData.length;
      for (var i = 0; i < len; i++) {
        // 以id作为索引存储元素，可以无需遍历直接快速定位元素
        temp[jsonData[i]["id"]] = jsonData[i];
      }
      for (var j = 0; j < len; j++) {
        var currentElement = jsonData[j];
        // 临时变量里面的当前元素的父元素，即pid的值，与找对应id值
        var tempCurrentElementParent = temp[currentElement["pid"]];
        // 如果存在父元素，即如果有pid属性
        if (tempCurrentElementParent) {
          // 如果父元素没有chindren键
          if (!tempCurrentElementParent["children"]) {
            // 设上父元素的children键
            tempCurrentElementParent["children"] = [];
          }
          // 给父元素加上当前元素作为子元素
          tempCurrentElementParent["children"].push(currentElement);
        }
        // 不存在父元素，意味着当前元素是一级元素
        else {
          result.push(currentElement);
        }
      }
      return result;
    },
    getAuthRuleInfo() {
      this.$ajax
        .get(this.$api.getAuthRuleInfo, { id: this.$route.params.id })
        .then(res => {
          this.initInfo = res;
          this.currentLevel = this.initInfo.level - 1;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    onChange(value) {
      this.list.forEach(item => {
        if (value === item.id) {
          this.currentLevel = item.level;
          return;
        }
      });
    },
    handleReset() {
      this.form.resetFields();
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    }
  },
  created() {
    this.getJurisdictionList();
    if (this.$route.name === "authorityNodeEdit") {
      this.getAuthRuleInfo();
    }
  }
};
</script>

<style scoped lang="less"></style>
